package com.example.myapplicationwork;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ProfileFragment extends Fragment {
    private static final String TAG = "ProfileFragment";
    private static final String ARG_USERNAME = "username";
    private static final String ARG_INTEREST = "interest";

    private String username;
    private String currentInterest;
    private TextView tvUsername;
    private TextView tvInterest;
    private Button btnSelectInterest;
    private Button btnLogout;
    private EditText etOldPassword;
    private EditText etNewPassword;
    private Button btnChangePassword;
    private TextView tvPasswordHistory;

    // 接口用于与宿主Activity通信
    public interface OnProfileInteractionListener {
        void onLogout();
        void onSelectInterest();
    }

    // 创建Fragment实例的静态方法
    public static ProfileFragment newInstance(String username, String interest) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USERNAME, username);
        args.putString(ARG_INTEREST, interest);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        if (getArguments() != null) {
            username = getArguments().getString(ARG_USERNAME);
            currentInterest = getArguments().getString(ARG_INTEREST, "未选择");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化视图
        initViews(view);

        // 显示用户名和兴趣
        tvUsername.setText("用户名: " + username);
        tvInterest.setText("兴趣: " + currentInterest);

        // 显示密码修改历史
        showPasswordHistory();

        // 设置按钮点击事件
        setButtonListeners();

        return view;
    }

    // 初始化视图
    private void initViews(View view) {
        tvUsername = view.findViewById(R.id.tv_username);
        tvInterest = view.findViewById(R.id.tv_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnLogout = view.findViewById(R.id.btn_logout);
        etOldPassword = view.findViewById(R.id.et_old_password);
        etNewPassword = view.findViewById(R.id.et_new_password);
        btnChangePassword = view.findViewById(R.id.btn_change_password);
        tvPasswordHistory = view.findViewById(R.id.tv_password_history);
    }

    // 设置按钮点击事件
    private void setButtonListeners() {
        // 选择兴趣按钮
        btnSelectInterest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof OnProfileInteractionListener) {
                    ((OnProfileInteractionListener) getActivity()).onSelectInterest();
                }
            }
        });

        // 退出登录按钮
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getContext())
                        .setTitle("确认退出")
                        .setMessage("是否确定要退出登录？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (getActivity() instanceof OnProfileInteractionListener) {
                                    ((OnProfileInteractionListener) getActivity()).onLogout();
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        // 修改密码按钮
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePassword();
            }
        });
    }

    // 更新兴趣显示
    public void updateInterest(String interest) {
        currentInterest = interest;
        if (tvInterest != null) {
            tvInterest.setText("兴趣: " + currentInterest);
        }
    }

    // 修改密码逻辑
    private void changePassword() {
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();

        if (oldPassword.isEmpty() || newPassword.isEmpty()) {
            Toast.makeText(getContext(), "旧密码和新密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取当前密码
        SharedPreferences sp = getActivity().getSharedPreferences("password_record", getActivity().MODE_PRIVATE);
        String currentPassword = sp.getString("current_password", "123456");

        if (!currentPassword.equals(oldPassword)) {
            Toast.makeText(getContext(), "旧密码输入错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (oldPassword.equals(newPassword)) {
            Toast.makeText(getContext(), "新密码不能与旧密码相同", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存新密码和修改记录
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("current_password", newPassword);

        // 记录修改时间和新密码
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date());
        String history = sp.getString("password_history", "") + newPassword + "(" + time + ");";
        editor.putString("password_history", history);

        editor.apply();

        // 显示修改成功提示并更新历史记录
        Toast.makeText(getContext(), "密码修改成功", Toast.LENGTH_SHORT).show();
        showPasswordHistory();

        // 清空输入框
        etOldPassword.setText("");
        etNewPassword.setText("");
    }

    // 显示密码修改历史
    private void showPasswordHistory() {
        SharedPreferences sp = getActivity().getSharedPreferences("password_record", getActivity().MODE_PRIVATE);
        String history = sp.getString("password_history", "无修改记录");
        tvPasswordHistory.setText(history);
    }

    // 生命周期方法
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
}
